
import dynamic from "next/dynamic";
import {useState,useEffect} from "react";
import { Input, Button, message,Select } from 'antd';
import { observer } from "mobx-react-lite";
import { useRouter } from "next/router";
import request from 'service/fetch'
import { useStore } from 'store/index'
import '@uiw/react-md-editor/markdown-editor.css'
import '@uiw/react-markdown-preview/markdown.css';
import styles from './index.module.scss';

const MDEditor = dynamic(() => import('@uiw/react-md-editor'), {ssr: false});

const newEditor: { (): JSX.Element; Layout: any; } = () => {
  // data
  const [title, setTitle] = useState('');
  const [content, setcontent] = useState('');
  const [allTags, setAllTags] = useState([]);
  const [tagIds, settagIds] = useState([]);

  useEffect(() => {
    request.get('/api/tag/get').then((res: any) => {
      if (res?.code === 0) {
        setAllTags(res?.data.allTags || []);
      }
    })
  }, []);

  // state
  const store = useStore()
  const { userId } = store.user.userInfo;
  const { push } = useRouter();
  // 标题
  const handleTitleChange = (e: any) => {
    setTitle(e.target?.value);
  };

  // 内容
  const handleContentChange = (content: any) => {
    setcontent(content);
  };

  // 发布
  const handlePublish = () => {
    if (!title) {
      message.error('请输入文章标题！');
      return;
    }
    if (!content) {
      message.error('请输入文章内容！');
      return;
    }
    if (!tagIds?.length) {
      message.error('请选择标签！');
      return;
    }
    request.post('/api/article/publish', {title, content,tagIds}).then((res: any) => {
      if (res?.code === 0) {
        userId ? push(`/user/${userId}`) : push('/');
        message.success('发布成功！');
      }else {
        message.error(res?.msg || '发布失败！');
      }
    });
  };

  const handleSelectTag = (value: any) => {
    settagIds(value)
  };

  return (
    <div className={styles.container}>
      <div className={styles.operation}>
        <Input className={styles.title} placeholder="请输入文章标题" value={title} onChange={handleTitleChange}></Input>
        <Select mode="multiple" allowClear placeholder="请选择标签" onChange={handleSelectTag} className={styles.tag}>
          {allTags?.map((tag: any) => <Select.Option key={tag.id} value={tag.id}>{tag.title}</Select.Option>)}
        </Select>
        <Button className={styles.button} type="primary" onClick={handlePublish}>发布</Button>
      </div>
      <MDEditor value={content} height={800} onChange={handleContentChange} />
    </div>
  )
};

// 定制layout不显示
newEditor.Layout = null;

export default observer(newEditor);